// 存储用户信息
import Cookies from "js-cookie";
import filterRouter from '../../utils/filterRouter'
import allRouter from '../../router/TcRouter'
import router from '../../router'

import {
    httpLogin
} from '../../api/login'
export default {
    namespaced: true,
    state: {
        // 用户信息
        user: JSON.parse(sessionStorage.getItem('user') || '{}'), 
        token: Cookies.get('token') || '',
        routerList: [], // 可以访问的路由
        author: sessionStorage.getItem('author') || '', // 用户权限
    },
    mutations: {
        getUser(state, payload) {
            state.user = payload.data;
            state.token = payload.token;
            state.author = payload.data.author;
            Cookies.set('token', payload.token);
            sessionStorage.setItem('user', JSON.stringify(payload.data))
            sessionStorage.setItem('author', payload.data.author)
        },
        // 存储已经过滤好的路由表
        setRouterList(state, payload) {
            state.routerList = payload
        }
    },
    actions: {
        // 登录请求
        // commit 调用 mutations的方法
        // dispatch 调用 actions的方法
        async actionsLogin({ commit, dispatch }, payload) {
            const res = await httpLogin(payload);
            Cookies.set('token', payload.token);
            await dispatch('actionsGetRouterList', res.data.data.author)
            await commit('getUser', res.data)

            return res;
            // return new Promise((resolve, reject) => {
            //     httpLogin(payload).then(res => {
            //         // 根据用户的权限来获取动态的路由表
            //         dispatch('actionsGetRouterList', res.data.data.author)
            //         commit('getUser', res.data)
            //         resolve(res);
            //     }, err => {
            //         reject(err);
            //     })
            // })
        },
        // 获取路由表
        async actionsGetRouterList({ commit }, payload) {
            // 根据用户的权限来获取动态的路由表 
            const res = filterRouter(allRouter, payload);

            // 动态的添加 路由表
            res.forEach(item => {
                router.addRoute(item)
            })
            // router.push(res[0].path);
            await commit('setRouterList', res);
        }
    }
}